package com.freely.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.freely.FR;
import com.freely.R;
import com.freely.component.activity.FreelyBaseActivity;
import com.freely.data.database.FreelyDatabase;
import com.freely.data.entities.User;
import com.freely.data.services.FreelyService;

import androidx.room.EmptyResultSetException;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends FreelyBaseActivity {
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        //检查是否已登陆
        Single<User> userMaybe = FreelyDatabase
                .getInstance()
                .userDAO()
                .queryUserByUserId(FR.USER_ID);

        Disposable disposable = userMaybe.subscribeOn(Schedulers.io())
                .subscribe(user -> {
                    //已登陆
                    Log.d(TAG, "viewInit: 已登陆");
                    Intent intent = new Intent(this, FreelyService.class);
                    Log.d(TAG, "onCreate: 开启服务");
                    startService(intent);
                    Thread.sleep(500);
                    HomeActivity.startActivity(this);
                    finish();
                }, throwable -> {
                    Thread.sleep(500);
                    if (throwable instanceof EmptyResultSetException) {
                        //未登录
                        Log.d(TAG, "init: 未登录");
                        LoginActivity.startActivity(this);
                    }
                    finish();
                });
        register(disposable);
    }

    public static  void startActivity(Context context){
        Intent intent = new Intent(context,MainActivity.class);
        context.startActivity(intent);
    }
}
